﻿using System.Threading.Tasks;
using FDSimpleModelGenerator.Common;
using FDSimpleModelGenerator.Entities;
using FDSimpleModelGenerator.Entities.Enums;
using FDSimpleModelGenerator.Entities.Exceptions;
using FDSimpleModelGenerator.IServices;

namespace FDSimpleModelGenerator.Services.MySql
{
    /// <summary>
    /// My Sql配置解析器
    /// </summary>
    public class MySqlDbConfigResolver : IDbConfigResolver
    {
        private readonly IExceptionThrowFactory _exceptionThrowFactory;

        public DbType DbType => DbType.MySql;

        public MySqlDbConfigResolver(IExceptionThrowFactory exceptionThrowFactory)
        {
            _exceptionThrowFactory = exceptionThrowFactory;
        }

        /// <summary>
        /// 获取连接串
        /// </summary>
        /// <param name="dbConfig"></param>
        /// <returns></returns>
        public string GetConnectionString(DbConfig dbConfig)
        {
            Check(dbConfig);
            return $"server={dbConfig.ServerName};database={dbConfig.Database};uid={dbConfig.UserName};port={dbConfig.Port};pwd={dbConfig.Password};Charset=utf8";
        }

        public async Task<string> GetConnectionStringAsync(DbConfig dbConfig)
        {
            return await Task.Run(() => GetConnectionString(dbConfig));
        }

        private void Check(DbConfig dbConfig)
        {
            if (dbConfig == null)
            {
                _exceptionThrowFactory.Throw<DbConfigException>("the database connection config was not set.");
            }

            if (dbConfig.ServerName.IsNullOrEmpty())
            {
                _exceptionThrowFactory.Throw<DbConfigException>("the database server was not set.");
            }

            if (dbConfig.Database.IsNullOrEmpty())
            {
                _exceptionThrowFactory.Throw<DbConfigException>("the database was not set.");
            }

            if (dbConfig.UserName.IsNullOrEmpty())
            {
                _exceptionThrowFactory.Throw<DbConfigException>("the database user name was not set.");
            }

            if (dbConfig.Password.IsNullOrEmpty())
            {
                _exceptionThrowFactory.Throw<DbConfigException>("the database password was not set.");
            }
        }
    }
}
